import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useUserStore } from './user'

interface UserProfile {
  avatar: string;
  username: string;
  phone: string;
  email: string;
  gender: number;
  region: string;
}

export const useProfileStore = defineStore('profile', () => {
  const userInfo = ref<UserProfile | null>(null)
  const loading = ref(false)
  const userStore = useUserStore()

  // 更新用户信息
  async function updateUserInfo(profile: UserProfile) {
    if (!userStore.userInfo?.access_token) {
      throw new Error('用户未登录')
    }

    loading.value = true
    try {
      const res = await uni.request({
        url: 'https://52d47b77.r34.cpolar.top/api/account/wechat/userinfo/',
        method: 'PUT',
        header: {
          'Authorization': `Bearer ${userStore.userInfo.access_token}`,
          'Content-Type': 'application/json'
        },
        data: {
          avatar: profile.avatar,
          username: profile.username,
          phone: profile.phone,
          email: profile.email,
          gender: profile.gender,
          region: profile.region
        }
      })

      if (res.statusCode === 200) {
        userInfo.value = res.data as UserProfile
        // 更新缓存
        uni.setStorageSync('userProfile', res.data)
        return userInfo.value
      } else {
        throw new Error('更新用户信息失败')
      }
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 清除用户信息
  function clearUserInfo() {
    userInfo.value = null
    uni.removeStorageSync('userProfile')
  }

  return {
    userInfo,
    loading,
    updateUserInfo,
    clearUserInfo
  }
})